import api from '../../../api/index'
import CONFIG from '../../../utils/config';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    
    tab: {
      active: 0,
      essaylist: [],
      list: [
          {
              name: '企业介绍',
              id: 'mirror/copy',
              index: 0,
              text:'1'
          },
          {
              name: '企业动态',
              id: 'mirror/biaozhun',
              index: 1,
              text:'2'
          },
          {
              name: '健康头条',
              id: 'ww',
              index: 2,
              text:'3'
          },
          {
              name: '加入我们',
              id: 'ww',
              index: 3  ,
              text:'4'
          }
      ],
  },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getkind()
  },
  getorg () {
    const actions = {
      data: {},
      head: {}
    };
    try {
      api.get(`/api/hxhealth/login/orgapp/${CONFIG.orgCode}/${CONFIG.appCode}`,actions,true).then((res) => {
        console.log(res);
        console.log(res.head['Set-Cookie']);
        if (res.head['Set-Cookie']) {
          wx.setStorageSync('accessToken', res.head['Set-Cookie']);
        } 
        this.getkind()
      });
    } catch (e) {
      console.error(e);
    }
  },
  getkind() {
    const actions = {
			data: {
				name: ''
			}
		} 
		api.post(`/api/hxhealth/article/kind`, actions).then(res => {
      console.log(res);
      this.setData({ 
        'tab.list': res
       })
      if(!wx.getStorageSync('newskindid')) {
        wx.setStorageSync('newskindid', res[0].id);
      }
      this.getload()
		}).catch(error => {
      this.getorg()
      // wx.showToast({
      //   title: error.faultstring,
      //   icon: 'none',
      //   duration: 3000
      // })
      return
    })
  },
  replaceSpecialChar(content) {
    content = content.replace(/&quot;/g,'"');
    content = content.replace(/&amp;/g, '&');
    content = content.replace(/&lt;/g, '<');
    content = content.replace(/&gt;/g, '>');
    content = content.replace(/&nbsp;/g, ' ');
    content = content.replace(/<p/gi, '<p class="p_class" ');
    content = content.replace(/<span/gi, '<span class="span_class" ');
    content = content.replace(/<img/gi, '<img class="img_class" ');
    return content;
  },
  getload(id){

    const actions = {
			data: {
				kindid: wx.getStorageSync('newskindid')
			}
		} 
        api.post(`/api/hxhealth/article/list`, actions)
            .then(res => {
                console.log(res);
                if(res.length > 0) {
                  this.setData({ 
                    essaylist: res,
                    'name': res[0].name?res[0].name:'',
                    'essayContent': this.replaceSpecialChar(res[0].content?res[0].content:''),
                    'imgUrl': res[0].images?res[0].images:''
                   }) 
                } else {
                  this.setData({ 
                    essaylist: [],
                   }) 
                }
            })
            .catch(e => {
                console.log(e)
            })
  },
  handlerDesicEnterprise(e) {
    const idx = e.currentTarget.dataset.index
    const kindid = e.currentTarget.dataset.kindid
    wx.navigateTo({
      url: `/redStarNews/pages/desic/index?idx=${idx}&desic=enterprise&kindid=${kindid}`,
    })
  },
  handlerDesicNews(e) {
    const idx = e.currentTarget.dataset.index
    const kindid = e.currentTarget.dataset.kindid
    wx.navigateTo({
      url: `/redStarNews/pages/desic/index?idx=${idx}&desic=news&kindid=${kindid}`,
    })
  },
  handlerTab(e) {
    // wx.showLoading({
    //     title: '加载中',
    // })
    // if (this.data.loading) {
    //     return
    // }
    console.log(e);
    const list = this.data.tab.list
    const index = e.currentTarget.dataset.index
    const ids = e.currentTarget.dataset.item.id
    wx.setStorageSync('newskindid', ids);
    this.getload()
    this.setData({
      'tab.active': index
    })

},
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getkind()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    wx.removeStorage({
      key: 'newskindid',
      success (res) {
      }
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },
  share() {},
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage(e) {
    console.log(e, '分享')
    const _this = this
    const idx = e.target.dataset.index
    const title = e.target.dataset.title
    const id = e.target.dataset.id
    const kindid = wx.getStorageSync('newskindid')
    const imageUrl = e.target.dataset.image
    console.log('用户分享调用111'+id)
    this.forward(id)
    return {
      title: title || '分享标题', // 分享标题
      path: `/redStarNews/pages/desic/index?idx=${idx}&desic=enterprise&kindid=${kindid}`, // 分享时打开的页面路径
      imageUrl: imageUrl || '', //（可选）分享的图片 URL
      // success: function (shareTickets) {
      //   console.log('分享成功', shareTickets);
      //   _this.forward(id)
      // },
      // fail: function (err) {
      //   console.log('分享失败', err);
      // }
    }
  },
  /**
   * 转发登记
   * @param {} id 
   */
  forward(id) {
    console.log('记录转发')
		api.get(`/api/hxhealth/article/forward/${id}`).then(res => {
      this.reloadList()
		}).catch(error => {
      wx.showToast({
        title: error.faultstring,
        icon: 'none',
        duration: 3000
      })
    })
  },
  /**
   * 收藏操作
   * @param {*} e 
   */
  optionCollect(e) {
    const id = e.currentTarget.dataset.id
    const collect = e.currentTarget.dataset.collect
    if(collect==1) {
      this.onUncollect(id)
    } else {
      this.onCollect(id)
    }
  },
  /**
   * 收藏
   * @param {} id 
   */
  onCollect(id) {
		api.get(`/api/hxhealth/article/collect/${id}`).then(res => {
      this.reloadList()
      wx.showToast({
        title: '收藏成功',
        icon: 'none',
        duration: 1000
      })
		}).catch(error => {
      wx.showToast({
        title: error.faultstring,
        icon: 'none',
        duration: 3000
      })
    })
  },
  /**
   * 取消收藏
   * @param {} id   
   */
  onUncollect(id) {
		api.get(`/api/hxhealth/article/uncollect/${id}`).then(res => {
      this.reloadList()
      wx.showToast({
        title: '取消收藏',
        icon: 'none',
        duration: 1000
      })
		}).catch(error => {
      wx.showToast({
        title: error.faultstring,
        icon: 'none',
        duration: 3000
      })
    })
  },
  reloadList() {
    const idx = this.data.tab.active
    const id = this.data.tab.list[idx].id
    this.getload(id)
  }
})